package utils

import (
	"fmt"
	"log"
	"os"
	"strings"
)

var InputTips = "请输入配置文件路径："
var ErrorTipsContent = "请检查文件内容"

// var TestFilePath = "C:\\Users\\79169\\Desktop\\event.xls"
// var TestFilePath = "E:\\GolandProjects\\convetConfig\\模板表1.xls"
var TestFilePath = "C:\\Users\\cheng\\Desktop\\trainpioneer\\玩家基础信息配置表.csv"

// 存储所有sheet的配置信息
var SheetData map[string][][]string

const (
	TS string = ".ts"
	GO string = ".go"
)

func GenConfigAllSheet(fileExt string, oldFileExt string) bool {
	for fileNameNew, fileData := range SheetData {
		filePath = GetNewPath(TestFilePath, oldFileExt) + fileNameNew + fileExt
		fmt.Println(filePath)

		fileContent := getContentStrBySheet(fileData, fileExt, fileNameNew)

		if fileContent == "" {
			continue
		}
		file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			fmt.Println("文件打开失败", err)
		}
		//及时关闭file句柄
		defer file.Close()

		//data := []byte("hello go\n")
		// 写入字节
		//file.Write(data)

		// 写入字符串
		file.WriteString(fileContent)

		// 确保写入到磁盘
		file.Sync()
	}
	return true
}

func getContentStrBySheet(fileData [][]string, ext string, sheetName string) string {
	if len(fileData) < 2 {
		fmt.Println(ErrorTipsContent)
		return ""
	}
	switch ext {
	case TS:
		return getTSStr(fileData, sheetName)
	case GO:
		return GetGoStr()
	}
	return ""
}

// TODO:生成go文件-可能需要模板
func GetGoStr() string {
	return ""
}

// 生成的ts文件内容，整理了格式
func getTSStr(fileData [][]string, sheetName string) string {
	strTop := "export const " + sheetName + " = {\n"
	strBottom := "}\n" + "export type " + sheetName + "Config = typeof " + sheetName
	strIndex := ""
	strBody := ""
	property := fileData[1]
	dataType := fileData[2]
	for i := 3; i < len(fileData); i++ {
		item := fileData[i]
		if isAllTempStr(item) {
			log.Println("配置文件中有空行.... 空行之下的都不处理")
			break
		}
		strIndex = item[0]
		itemTop := "    " + "\"" + item[0] + "\"" + ": {\n"
		itemBottom := "    },\n"
		itemBody := ""
		for index, pro := range property {
			itemValue := confirmType(item, index, dataType[index])
			//itemBody += "        	" + pro + ": " + "\"" + item[index] + "\"" + ",\n"
			itemBody += "        " + pro + ": " + itemValue + ",\n"
		}
		strBody += itemTop + itemBody + itemBottom
	}
	return strTop + strBody + strBottom + "[\"" + strIndex + "\"]" + "\n"
}

func confirmType(item []string, index int, dataType string) string {
	if dataType == "string" {
		return "\"" + item[index] + "\""
	}
	if dataType == "boolean" {
		return strings.ToLower(item[index])
	}
	return item[index]
}

func isAllTempStr(item []string) bool {
	for _, s := range item {
		if s != "" {
			return false
		}
	}
	return true
}
